package cn.dsp.admin.config;

import cn.dsp.admin.mapper.AdminMapper;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

/**
 * 自定义 密码验证类
 * @author q
 *
 */
public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {

    @Autowired
    private AdminMapper mapper;

    @Override
    public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {
                System.out.println("进行密码验证！");
        MyUsernamePasswordToken token = (MyUsernamePasswordToken) authcToken;
                System.out.println(token.getSalt());
        Object tokenCredentials = encrypt(String.valueOf(token.getPassword()),token.getSalt());
        Object accountCredentials = getCredentials(info);
        //将密码加密与系统加密后的密码校验，内容一致就返回true,不一致就返回false
        return equals(tokenCredentials, accountCredentials);
    }

    //将传进来密码加密方法
    private String encrypt(String password,String salt) {
        //加密规则：在原密码的左侧和右侧均拼接盐值，循环三次
        String str = salt + password + salt;
        for (int i = 0; i < 5; i++) {
            str = DigestUtils.md5DigestAsHex(str.getBytes());
        }
        return str;
    }
}